package com.huawei.leetcode;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Code1 {
    public static void main(String[] args) {
        Code1 code1 = new Code1();
        int[] nums = {3,3};
        code1.twoSum(nums, 6);
    }

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }

    public int[] twoSum1(int[] nums, int target) {
        int[] arr = new int[2];

        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            List<Integer> list = new ArrayList<>();
            if (map.get(nums[i]) != null) {
                list = map.get(nums[i]);
            }
            list.add(i);
            map.put(nums[i], list);
        }
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                List<Integer> list = map.get(nums[i]);
                arr[0] = list.get(0);
                if (target - nums[i] == nums[i] && list.size() >= 2) {
                    arr[1] = list.get(1);
                    break;
                }
                if(target - nums[i] != nums[i]){
                    arr[1] = map.get(target - nums[i]).get(0);
                    break;
                }
            }
        }
        return arr;
    }
}
